<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserAddressRequest;
use App\Models\UserAddress;
use Illuminate\Http\Request;

class UserAddressesController extends Controller
{
    public function index(Request $request){
        return view('user_addresses.index',[
            'addresses'=>$request->user()->addresses,
        ]);
    }
    public function create(){
        return view('user_addresses.create_and_edit', ['address'=>new UserAddress]);
    }
    public function edit(UserAddress $address){
        $this->authorize('own', $address);
        return view('user_addresses.create_and_edit', ['address'=>$address]);
    }
    public function update(UserAddressRequest $request, UserAddress $address){
        $address->update($request->only([
            'province', 'city', 'district',  'address', 'zip', 'contact_name', 'contact_phone'
        ]));
        return redirect()->route('user_addresses.index');
    }
    public function destroy(Request $request, UserAddress $address){
        $this->authorize('own', $address);
        $address->delete();
//        if(request()->expectsJson())      // 不准！
        if($request->expectsJson())
            return [];
        return redirect()->route('user_addresses.index');
    }
    public function store(UserAddressRequest $request){
        // 改成 $request->user()->addresses()->insert() 不行？！
        $request->user()->addresses()->create($request->only([
            'province', 'city', 'district',  'address', 'zip', 'contact_name', 'contact_phone'
        ]));
        return redirect()->route('user_addresses.index');
    }
}
